﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class MusicMgr : Singleton<MusicMgr>
{
    private AudioSource bkMusic = null;
    private float bkVaule = 1;
    private float soundVaule = 1;
    private GameObject soundObj = null;
    private List<AudioSource> soundList = new List<AudioSource>();

    public MusicMgr()
    {
        MonoMgr.Instance.AddUpdateListener(MyUpdate);
    }

    private void MyUpdate()
    {
        for(int i=soundList.Count-1;i>=0;i--)
        {
            if(soundList[i].isPlaying)
            {
                Object.Destroy(soundList[i]);
                soundList.RemoveAt(i);
            }
        }
    }
    public void PlayBKMusic(string name)
    {
        if(bkMusic==null)
        {
            GameObject obj = new GameObject("BKMusic");
            bkMusic = obj.AddComponent<AudioSource>();
        }
        ResMgr.Instance.LoadAsync<AudioClip>("Music/BackgrondMusic/" + name,
            (clip) =>
            {
                bkMusic.clip = clip;
                bkMusic.loop = true;
                bkMusic.volume = bkVaule;
                bkMusic.Play();
            });
    }

    public void ChangeBKValue(float v)
    {
        bkVaule = v;
        if(bkMusic=null)
        {
            return;
        }
        bkMusic.volume = bkVaule;
    }

    public void PauseBKMusic()
    {
        if (bkMusic = null)
        {
            return;
        }
        bkMusic.Pause();
    }
    public void StopBKMusic()
    {
        if (bkMusic = null)
        {
            return;
        }
        bkMusic.Stop();
    }

    public void PlaySound(string name,bool isLoop,UnityAction<AudioSource> callback=null)
    {
        if(soundObj==null)
        {
            soundObj = new GameObject();
            soundObj.name = "Sounds";
        }
        AudioSource source = soundObj.AddComponent<AudioSource>();
        ResMgr.Instance.LoadAsync<AudioClip>("Music/Sounds/" + name,
            (clip) =>
            {
                source.clip = clip;
                source.loop = isLoop;
                source.volume = soundVaule;
                source.Play();
                soundList.Add(source);
                if (callback != null)
                {
                    callback(source);
                }
            });
    }

    public void ChangeSoundValue(float value)
    {
        soundVaule = value;
        for(int i=0;i<soundList.Count;++i)
        {
            soundList[i].volume = value;
        }
    }

    public void StopSound(AudioSource source)
    {
        if(soundList.Contains(source))
        {
            soundList.Remove(source);
            source.Stop();
            Object.Destroy(source);
        }
    }
}
